package com.universest.swordholder.model

import android.util.Log
import com.universest.swordholder.data.dao.LongText
import com.universest.swordholder.data.dao.Passage
import com.universest.swordholder.data.getUserDb
import com.universest.swordholder.data.repository.BookRepository
import com.universest.swordholder.data.repository.LongTextRepository
import com.universest.swordholder.data.repository.PassageRepository
import com.universest.swordholder.data.repository.VolumeRepository
import kotlinx.coroutines.flow.firstOrNull

class NovelInfoHelper(private val bookId: Int) {

    private val bookRepository = BookRepository(getUserDb())
    private val volumeRepository = VolumeRepository(getUserDb())
    private val passageRepository = PassageRepository(getUserDb())
    private val longTextRepository = LongTextRepository(getUserDb())

    suspend fun getNovelInfo(): String {
        val book = bookRepository.getBookById(bookId).firstOrNull()
        if (book == null) {
            throw Exception("书籍未找到")
        }
        val novelInfo = StringBuilder()
        novelInfo.append("书名：${book.bookName}\n")
        novelInfo.append("简介：${book.bookDescription}\n")
        return novelInfo.toString()
    }

    suspend fun getPassageSummary(passageId: Int): String {
        val passage = passageRepository.getPassageById(passageId).firstOrNull()
        return passage?.simpleContentId?.let {
            longTextRepository.getTextById(it).firstOrNull()?.content ?: ""
        } ?: ""
    }

    suspend fun getPassageContent(passageId: Int): String {
        val passage = passageRepository.getPassageById(passageId).firstOrNull()
        return passage?.contentId?.let {
            longTextRepository.getTextById(it).firstOrNull()?.content ?: ""
        } ?: ""
    }

    suspend fun setPassageSummary(passageId: Int, summary: String) {
        var passage = passageRepository.getPassageById(passageId).firstOrNull()
        if (passage == null) {
            return
        }
        var longText = longTextRepository.getTextById(passage.simpleContentId).firstOrNull()
        if (longText == null) {
            longText = LongText(content = summary)
            longText = longText.copy(textId = longTextRepository.insert(longText).toInt())
            passage = passage.copy(simpleContentId = longTextRepository.insert(LongText(content = summary)).toInt())
            passageRepository.update(passage)
        }
        longText = longText.copy(content = summary)
        longTextRepository.update(longText)
    }

    suspend fun getVolumeSummary(volumeId: Int): String{
        val volume = volumeRepository.getVolumeById(volumeId).firstOrNull()
        return when(volume?.summaryId ?: -1){
            -1 -> ""
            else -> longTextRepository.getTextById(volume?.summaryId?:-1).firstOrNull()?.content ?: ""
        }
    }

    suspend fun setVolumeSummary(volumeId: Int, summary: String) {
        var volume = volumeRepository.getVolumeById(volumeId).firstOrNull()
        if (volume == null) {
            return
        }
        var longText = longTextRepository.getTextById(volume.summaryId).firstOrNull()
        if (longText == null) {
            longText = LongText(content = summary)
            longText = longText.copy(textId = longTextRepository.insert(longText).toInt())
            volume = volume.copy(summaryId = longText.textId)
            volumeRepository.update(volume)
        }else{
            longText = longText.copy(content = summary)
            longTextRepository.update(longText)
        }
    }

    suspend fun setVolumeUseSummary(volumeId: Int, useSummary: Boolean){
        var volume = volumeRepository.getVolumeById(volumeId).firstOrNull()
        if (volume == null) { return }
        volumeRepository.update(volume.copy(summaryUse = useSummary))
    }

    suspend fun getSummaryBeforeVolume(volumeId: Int): String{
        val volume = volumeRepository.getVolumeById(volumeId).firstOrNull()
        if(volume == null)return ""
        val firstPassage = passageRepository.getPassagesByBookIdAndVolumeId(bookId, volumeId).firstOrNull()?.firstOrNull()
        if(firstPassage == null) return ""
        return getPreviousChapterSummaries(firstPassage.passageId,0,bookId)
    }

    suspend fun getSummariesOfVolumePassages(volumeId: Int): String{
        val volume = volumeRepository.getVolumeById(volumeId).firstOrNull()
        if(volume == null)return ""
        val passages = passageRepository.getPassagesByBookIdAndVolumeId(bookId, volumeId).firstOrNull()?:emptyList()
        val stringBuilder = StringBuilder()
        stringBuilder.append("== ${volume.name}== \n\n")
        passages.forEach { passage->
            stringBuilder.append("== ${passage.title} == \n\n")
            stringBuilder.append(getPassageSummary(passage.passageId))
            stringBuilder.append("\n\n")
        }
        return stringBuilder.toString()
    }

    /**
     * 获取指定段落之前若干段落的内容，包括标题、正文或摘要。
     *
     * @param passageId 当前段落ID，用于定位当前位置
     * @param entirePassageCount 需要完整显示的前序段落数量
     * @param bookId 所属书籍ID，用于获取相关卷和段落信息
     * @return 包含前序章节内容的字符串，格式化后可直接展示
     */
    suspend fun getPreviousChapterSummaries(passageId: Int, entirePassageCount: Int, bookId: Int): String {
        // 获取书籍的所有卷
        val volumes = volumeRepository.getVolumeByBookId(bookId).firstOrNull() ?: emptyList()

        // 创建 volumeId -> volumeIndex 映射表用于快速查询
        val volumeIndexMap = volumes.withIndex().associate { it.value.volumeId to it.index }

        // 收集所有段落（不分卷+各卷）
        val passages = mutableListOf<Passage>()
        val volumeFirstPassageIndex = IntArray(volumes.size) { -1 }

        // 添加无归属卷的段落
        passageRepository.getPassagesByBookIdAndVolumeId(bookId, -1).firstOrNull()?.forEach {
            passages.add(it)
        }

        // 添加每个卷下的段落，并记录该卷第一个段落在总列表中的位置
        volumes.forEachIndexed { index, volume ->
            passageRepository.getPassagesByBookIdAndVolumeId(bookId, volume.volumeId).firstOrNull()?.let {
                volumeFirstPassageIndex[index] = passages.size
                it.forEach { passage ->
                    passages.add(passage)
                }
            }
        }

        // 查找当前段落的位置
        var currentPassageIndex = passages.indexOfFirst { it.passageId == passageId }
        if (currentPassageIndex < 0) currentPassageIndex = passages.size - 1

        val stringBuilder = StringBuilder()
        val skipVolume = mutableSetOf<Int>()
        // 按顺序处理每一个段落，构建输出文本
        for (index in passages.indices) {
            val passage = passages[index]
            if(skipVolume.contains(passage.volumeId)){
                continue
            }
            val volume = volumeRepository.getVolumeById(passage.volumeId).firstOrNull()
            val volumeIndex = volumeIndexMap[passage.volumeId] ?: -1
            // 若是某卷的第一个段落，则插入卷名标识
            if (volumeIndex >= 0 && index == volumeFirstPassageIndex[volumeIndex]) {
                stringBuilder.append("==${volumes[volumeIndex].name}==\n\n")
                // 当前卷需要显示摘要，且不是当前段落所在的卷时，添加卷摘要内容
                if(volume?.summaryUse == true && volume.summaryId != -1 && volume.volumeId != passages[currentPassageIndex].volumeId){
                    val longText = longTextRepository.getTextById(volume.summaryId).firstOrNull()
                    if (longText != null && longText.content.isNotBlank()) {
                        skipVolume.add(volume.volumeId)
                        stringBuilder.append("卷摘要：")
                        stringBuilder.append(longText.content)
                        stringBuilder.append("\n\n\n")
                        continue
                    }
                }
            }

            // 只处理在当前段落之前的段落
            if (index < currentPassageIndex) {
                try {
                    // 根据距离决定是否使用全文还是摘要
                    if (index >= currentPassageIndex - entirePassageCount) {
                        stringBuilder.append("${passage.title}\n\n")
                        stringBuilder.append(getPassageContent(passage.passageId))
                        stringBuilder.append("\n\n\n")
                    } else {
                        stringBuilder.append("${passage.title}（摘要）\n\n")
                        stringBuilder.append(getPassageSummary(passage.passageId))
                        stringBuilder.append("\n\n\n")
                    }
                } catch (e: Exception) {
                    Log.e("NovelInfoCollector", "getPreviousChapters error", e)
                }
            } else {
                break
            }
        }
        return stringBuilder.toString()
    }


}